package org.snare.alumni.config;

import com.auth0.jwt.exceptions.TokenExpiredException;
import org.snare.spider.toolkit.jwt.JwtUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT 拦截认证
 *
 * @author DASH
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {

        //跨域请求会首先发一个option请求，直接返回正常状态并通过拦截器
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String token = request.getHeader("Jwt");
        if (token != null) {
            JwtUtils.verifyJWT(token);
        } else {
            throw new TokenExpiredException("");
        }
        return true;
    }

}